<?php
namespace app\api\controller;
/**
 * 子系统访问权限控制器(app\api\controller)
 * 用于验证账户信息 登入信息 获取权限信息等
 */
use think\Controller;
use think\Db;
use think\Cache;
use app\api\model\ApiAuthorizationModel;
use app\admin\model\AdminMenuModel;
use app\admin\model\AccessModel;
use app\admin\model\ModuleMenuModel;
use app\api\model\ApiAccessAuthorityModel;
use app\api\controller\ApiAccessAuthorityController;
use plugins\appmarket\model\AdminIndexModel as AppmarketAdminIndexModel;
use plugins\appmarket\controller\ConfigController as AppmarketConfigController; 
use plugins\appmarket\model\ModulePurchaseHistoryModel; 


/**
 *应用市场api
 * 
 */
class ApiModuleStoreController extends Controller
{
    /**
     * 初始化方法
     */
    public function _initialize()
    {
        //验证签名
        $param = $this->request->param();
		ApiAccessAuthorityController::signVerify( $param , false );        
    }   


    /**
     * 获取应用市场列表
     */
    public function appList()
    {
        $data = $this->request->param();
        //获取当前请求用户的userId查询购买记录用
		$companyId= Db::name( 'company' )->where( 'aid' , '==='.$data [ 'appid' ] )->value( 'id' );
        $userId = Db::name('user_attach')->where( 'company_id' , $companyId )->value('user_id');
        //搜索参数
	
		
		$search = [
            'categoryTmp'   =>      isset( $data [ 'categoryTmp' ] ) ? $data [ 'categoryTmp' ] : '0/全部分类' ,
            'category'      =>      isset( $data [ 'categoryTmp' ] ) ? substr( $data ['categoryTmp'] , 0 , strpos( $data ['categoryTmp'] , '/' ) ) : 0 ,
            'categoryName'  =>      isset( $data [ 'categoryTmp' ] ) ? substr( $data ['categoryTmp'] , strpos( $data ['categoryTmp'] , '/' )+1 ) : '全部分类' ,
            'payment'       =>      isset( $data [ 'payment' ] ) ? $data [ 'payment' ] : 100,
			'buy'       =>      isset( $data [ 'buy' ] ) ? $data [ 'buy' ] : 0,
            'keywords'      =>      isset( $data [ 'keywords' ] ) ? $data [ 'keywords' ] : '',
            'search'        =>      isset( $data [ 'search' ] ) ? $data [ 'search' ] : null
        ]; 

        $adminIndexModel = new AppmarketAdminIndexModel();
        $field = 'id,name,title,putway,version,introduce,status,describe,price,author,author_id,category';
        $list = $adminIndexModel->appList( $userId, $field , $search );

        $categoryList = Db::name( 'module_category' )->select()->toArray();
		
		$moduleList = $this->getModuleStoreModuleList();

        $data = [
            'search' => $search,
            'categoryList' => $categoryList,
            'list' => $list,
			'moduleList' => $moduleList
        ];
        return zy_json_echo( true, '成功' , $data);        
    }
	
	//获取应用市场的模块列表
	private function getModuleStoreModuleList()
	{
		$list = Db::name('module_store')->group('title')->column('title');
		return $list;
	}

    /**
     * 查看模块详情页面
     *
     */
    public function particular( )
    {
        $param = $this->request->param();
        if( !isset( $param [ 'id' ] ) || empty( $param [ 'id' ] )  ){
            return zy_json_echo( false , 'id不存在!' );
        }
        $id = $param [ 'id' ] ;
        $module = Db::name( 'module_store' )->where( 'id' , $id )->field( 'id,name,title, describe,version,author,author_id,introduce,warning,price,preview,add_time,status,step,category')->find();

         //获取地址
        $address = AppmarketConfigController::getDownloadHostAddress();
        $main = ( $address ['main'] [ 'status' ] == 1 ) ? $address ['main'] [ 'address' ]: '' ;
        $minor = ( $address [ 'minor' ] [ 'status' ] == 1 ) ? $address [ 'minor' ] [ 'address' ] : '' ;
        $previewList = [];
        if( !empty($module['preview']) ){
            $previewList = explode(',', $module['preview']);
        }
        $previewList = array_map(function( $path ) use  ( $main, $minor ) {
            $newPath  = '';
            if( !empty( $main ) ){
                $newPath = $main.'/'.$path;
            }else{
                if( !empty( $minor ) ){
                    $newPath = $minor.'/'.$path;
                }
            }
            return $newPath;
        }, $previewList ) ;
        unset( $module [ 'preview' ] );
        $data = [
            'previewList' => $previewList,
            'module' => $module
        ];
        return zy_json_echo( true , '成功' , $data );
    }

    /**
     * 获取下载地址
	 *地址: api/api_module_store/getSourceAddr
	 *所需参数 ：
	 *$id 模块id
	 *$pid 协议码
	 *$cid 子系统所在的公司id
     */
    public function getSourceAddr()
    {
        $param = $this->request->param();
        if( !isset( $param [ 'id' ] ) || empty( $param [ 'id' ] )  ){
            return zy_json_echo( false , 'id不存在!' );
        }
        if( !isset( $param [ 'pid' ] ) || empty( $param [ 'pid' ] )  ){
            return zy_json_echo( false , '参数错误,请检查（pid）!' );
        }

        $id = $param [ 'id' ] ;
        //验证协议码  -> 检查账户信息 获取公司信息
        $this->verifyPermissionCode( false ) ;

        $find = Db::name('module_store')->where('id' , $id )->find();
        if( empty($find) ){
            return zy_json_echo( false , '未找到相应的数据!' );
        }
 
		
        $path = $find [ 'resource' ] ;
        //获取下载地址
        $address = AppmarketConfigController::getDownloadHostAddress();
        if( empty( $path ) ){
            return zy_json_echo(false, '文件路径不存在!' );
        }
        $main = ( $address ['main'] [ 'status' ] == 1 ) ? $address ['main'] [ 'address' ].'/'.$path : '' ;
        $minor = ( $address [ 'minor' ] [ 'status' ] == 1 ) ? $address [ 'minor' ] [ 'address' ].'/'.$path : '' ;
        return zy_json_echo(true , '成功!' , [ 'main' => $main , 'minor' => $minor ] );
    }

    /**
     * 获取购买记录接口
     * 地址: api/api_module_store/boughtHistory()
     * $id 模块id
     * $pid 协议码 
     * $operator 操作者信息 (执行下载操作的用户信息) base64_encode('用户名,密码');
     * $cid 子系统所在的公司id
     * 返回码定义:
     * 200成功 表示已购买
     * 201 未查询到购买记录,需跳转到付款页面
     * 其他错误请参考返回的错误信息
     */
    public function boughtHistory()
    {
        $param = $this->request->param();
        if( !isset( $param [ 'id' ] ) || empty( $param [ 'id' ] )  ){
            return zy_json_echo( false , '参数错误(id),请检查!' );
        }
        if( !isset( $param [ 'pid' ] ) || empty( $param [ 'pid' ] )  ){
            return zy_json_echo( false , '验证信息错误(pid),请检查!' );
        }
        if( !isset( $param [ 'cid' ] ) || empty( $param [ 'cid' ] )  ){
            return zy_json_echo( false , '参数错误(cid),请检查!' );
        }
        $cid = $param [ 'cid' ];//子系统所在的公司id
        
        //验证协议码  -> 检查账户信息 获取公司信息
        $this->verifyPermissionCode( ) ;
        $moduleId = $param['id'];
        //验证通过,检查是否已经购买
        $where = [
            'company_id' => $cid,
            'module_id' => $moduleId,
			'status' => 1
        ]; 
        $res = $this->checkAccount();
		//return zy_json_echo(false , '' , $res);
        $find = Db::name( 'module_purchase_history' )->where( $where )->find();
        if( empty( $find ) ){
			$module = Db::name( 'module_store' )->where( 'id' , $moduleId )->find();
            //未获取到购买信息 进行购买  或者 免费的app
            if( $res [ 'id' ] == 8 || $module [ 'price' ] == 0  ){
                $userId = Db::name( 'user_attach' )->where( 'company_id' , $res [ 'id' ] )->value( 'user_id' );
                //开发者购买信息 免支付购买
                $this->addBoughtRecord( $userId , $cid , $moduleId ,  0 ,  $module['price'] , 0, 1 ,1 );
            }else{
                //普通用户购买 需要跳转到购买页面
                return zy_json_echo(false, '需跳转到支付页面' , '' , 201 );
            }
        }
        return zy_json_echo( true, '已购买');
    }


    /**
     * 验证协议码
	 *$rule 是否严格模式进行检测
     */
    private function verifyPermissionCode( $rule = true )
    {
        $param = $this->request->param();
		//严格模式检查用户帐户信息 
        if( $rule == true ) {
			//检查账户信息
			$res = $this->checkAccount();
		}
        if( !isset( $param [ 'cid' ] ) || empty( $param [ 'cid' ] )  ){
            
            return zy_json_echo( false , '参数错误(cid),请检查!' );
        }
        if( !isset( $param [ 'pid' ] ) || empty( $param [ 'pid' ] )  ){
            
            return zy_json_echo( false , '参数错误(pid),请检查!' );
        }
        $cid = $param [ 'cid' ] ;
        
        $agreementCodeName = 'AGREEMENT_CODE_TO_API_STORE_'.$cid;
        //读取缓存协议码
        $cachePermissionCode = Cache::get( $agreementCodeName );
        if( empty( $cachePermissionCode)  ){
            //协议吗过期,清除过期信息 用户需要重新登录
            return zy_json_echo( false, '验证信息已过期' , '' , 10018 ) ;
        }
        $permissionCode = $param [ 'pid' ];
        if ( $cachePermissionCode !== $permissionCode ){
            return zy_json_echo( false, '验证信息失败!'.$cachePermissionCode , '' , 10019 ) ;
        }
        return true;
    }

    /**
     *购买模块支付成功后的回调
     */
    public function boughtApp()
    {
        $param = $this->request->param();
        //验证协议码  -> 检查账户信息 获取公司信息
        $res = $this->verifyPermissionCode( );
        $userId = 1;
        $companyId = Db::name( 'user_attach')->where( 'user_id' , $userId )->value( 'company_id' );
        $moduleId = 10;
        $module = Db::name( 'module_store' )->where ( 'id' , $moduleId )->find();
        //过期时间
        $expire = time()+(1000*24*60*60);
        //保存购买记录
        $res = $this->addBoughtRecord( $userId , $companyId, $modulId ,  $expire ,  $module['price'] , 0, 1 );
        //返回回调成功        
    }
    
   
    /**
     *登陆接口操作者获取许可
     *所需参数 $operator base64_encode(用户名,密码)
     *返回 permissionCode 许可码
     */
    public function operatorPermission()
    {
        $param = $this->request->param();
        if( !isset( $param [ 'cid' ] ) || empty( $param [ 'cid' ] )  ){
            return zy_json_echo( false , '参数错误(cid),请检查!' );
        }
        $cid = $param [ 'cid' ] ;
        //检查账户信息
        $this->checkAccount();
        //验证成功
        //生成协议码
        $param = $this->request->param();
        $operator = $param[ 'operator' ];
        $data =  [
            'id' => $operator,
            'time' => time()
        ]; 
        //缓存协议码 缓存名称 AGREEMENT_CODE_TO_API_STORE_加上公司(登入系统的公司id )
        $agreementCodeName = 'AGREEMENT_CODE_TO_API_STORE_'.$cid;
        if( Cache::has( $agreementCodeName ) && !empty( $agreementCodeName ) ){
            $agreementCode = Cache::get( $agreementCodeName );
        }else{
            $agreementCode = ApiAccessAuthorityController::createAgreement( $data );
            Cache::set( $agreementCodeName , $agreementCode ,600 );
        }
        $returnData = [
            'permissionCode' => $agreementCode
        ];
        return zy_json_echo( true , '登入成功!' , $returnData );
    }

    /**
     * 验证账户信息
     */
    private function checkAccount()
    {
        $param = $this->request->param();
        if( !isset( $param [ 'operator' ] ) || empty( $param [ 'operator' ] ) ){
            return zy_json_echo( false , '参数缺失(operator)!'  );
        }
        $sub = base64_decode( str_replace( ' ' , '+' , $param [ 'operator' ] ) );
        $sub = explode( ',' , $sub );
        $userLogin = reset($sub);
        $userPassword = end($sub);
        $accessAuthority = new ApiAccessAuthorityModel();
        $res = $accessAuthority->accountPermissionByPwd( $userLogin , $userPassword );
        if( $res [ 'status' ] == false ){
            return zy_json_echo( false, $res [ 'message' ] , '' , $res [ 'code' ] );
        }
        return $res;
    }

    /**
     * 添加记录
     * (用户id ,公司Id,模块id,过期时间,购买金额,购买类型,操作类型)
     */
    private function addBoughtRecord( $userId , $companyId, $modulId ,  $expire = 0 ,  $paymentAmount = 0 , $paymentType = 0, $operateType =0 , $status = 0 )
    {
        $userName = Db::name( 'user' )->where( 'id' , $userId )->value('user_login');
        $order_num = 'M'.date('YmdHis').mt_rand(  11111, 99999);
        $data = [
            'order_num' => $order_num,
            'company_id' => $companyId,
            'module_id' => $modulId,
            'user_id' => $userId,
            'user_name' => $userName,
            'expire' => $expire,//0永久
            'payment_amount' => $paymentAmount,
            'payment_type' => $paymentType,
            'add_time' => time(),
            'operate_type' => $operateType, // 0 用户购买  1 开发者购买 
            'status'=> $status 
        ];
        //保存数据
        $moduleModel = new ModulePurchaseHistoryModel();
        $result = $moduleModel->bought( $data );
        if( $result ){
            return [ 'order_num'=> $order_num , 'id' => $result   ];
        }
        return $result;
    }
    
    
    /**
     * 获取微信支付码方法
     * api地址: api/api_module_store/wechatpayCode
     * 所需参数:
     *  $order_sn:订单编号
     *  $mid: 模块id
     *  $title: 标题
     *  $operator:操作者信息 base64_encode(用户名,密码)
     *  $cid 公司id
     *  $pid 协议码
     * 返回数据:
     *  100 参数错误 
     *  101 模块不存在 mid错误  
     */
    public function wechatPayCode()
    {
        $param = $this->request->param();
        if( !isset( $param [ 'mid' ] ) || empty( $param [ 'mid' ] ) ){
            return zy_json_echo( false , '参数缺失(mid)!' ,'' ,100  );
        }
        if( !isset( $param [ 'title' ] ) || empty( $param [ 'title' ] ) ){
            return zy_json_echo( false , '参数缺失(title)!','' ,100   );
        }
        if( !isset( $param [ 'title' ] ) || empty( $param [ 'title' ] ) ){
            return zy_json_echo( false , '参数缺失(title)!' ,'' ,100  );
        }
        //验证协议码  -> 检查账户信息 获取公司信息
        $res = $this->verifyPermissionCode();
        //wechat_native($uid=null,$order_sn=null,$money=null,$title=null,$module=null,$type=null,$isModule=false)
        $findModule = Db::name( 'module_store' )->where( 'id' , $param [ 'mid' ]  )->find();
        if( empty ($findModule) ){
            return zy_json_echo( false , '模块不存在' ,'', 101 );
        }
		$companyId = $param [ 'cid' ] ;//公司id
		$money = $findModule['price'];
        //$money = 0.01;
		$userId  = Db::name( 'user_attach' )->where( 'company_id' , $param['cid'] )->value( 'user_id' );
        //添加订单记录
        $result = $this->addBoughtRecord( $userId , $companyId, $param['mid'] , 0 ,  $money , 0 , 0 );
        if( !$result ){
            return zy_json_echo( false , '添加记录失败,请稍后再试!' , '' ,202 );
        }
        
        $order_sn = $result [ 'order_num' ];
        $title = $param [ 'title' ] ;
        $module = 'Appmarket';
        
        $type = 1 ; 
		
        $param = [ 
            'uid'=> $companyId,
            'order_sn' => $result [ 'order_num' ],
            'money' => ((int)($money*100)),
            'title' => $title,
            'module' => $module,
            'type' => $type,
            'isModule'=>true
        ];
        
        
        $apiReturnData = getModuleApiData( 'Appmarket' , 'get_wechat_pay_code' , $param );
        if( isset( $apiReturnData [ 'status' ] ) && $apiReturnData [ 'status' ] == 'success' && isset( $apiReturnData [ 'data' ] ) ){
            $apiReturnData [ 'data' ] = [
                'qsrc' => cmf_get_domain().'/plugin/wechat_pay/api_index/wechat_native_qrcode?data='.$apiReturnData['data'],
                'order_num' => $result [ 'order_num' ] 
            ];   
        }
        echo json_encode( $apiReturnData  , JSON_UNESCAPED_UNICODE );exit();
    }

    /**
     * 获取订单信息
     * @return [type] [description]
     */
    public function getOrderStatus()
    {
        $param = $this->request->param();
        if( !isset( $param [ 'order_num' ] ) || empty( $param [ 'order_num' ] ) ){
            return zy_json_echo( false , '参数缺失(order_num)!' ,'' ,100  );
        }
        $status = Db::name( 'module_purchase_history' )->where( 'order_num' , $param [ 'order_num' ] )->value( 'status' );
		if( empty($status) ){
			return zy_json_echo( false, '未支付！'  );
		}
		return zy_json_echo(true , '已支付！');
    }
    
}